﻿using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using System.Configuration;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace SNARF.Framework.ActiveRecord
{
    public static class SessionManager
    {
        private static SessionProviderBase provider;
        private static SNARFConfigurationHandler config;

        static SessionManager()
        {
            config = 
                (SNARFConfigurationHandler)ConfigurationManager.GetSection("snarf-configuration/session-provider");

            if (config == null)
                config = new SNARFConfigurationHandler();

            provider = (SessionProviderBase)Activator.CreateInstance(config.AssemblyName, config.TypeName, null).Unwrap();
            

            CheckProvider();
            
        }

        public static ISession CurrentSession
        {
            get
            {
                CheckProvider();
                return provider.CurrentSession;
            }
        }

        private static void CheckProvider()
        {
            if (provider == null)
            {
                throw new ApplicationException("The provider " + config.AssemblyName + "." + config.TypeName + " could not be loaded.");
            }
        }
        
        public static DataSet GetDataSet(string sql)
        {
            return GetDataSet(sql, new Dictionary<string, object>() );
        }

        public static DataSet GetDataSet(string sql, Dictionary<string, object> parameters )
        {
            SqlConnection connection = (SqlConnection)SessionManager.CurrentSession.Connection;
            SqlCommand command = new SqlCommand(sql, connection);

            foreach (string name in parameters.Keys)
            {
                SqlParameter sqlParam = new SqlParameter(name, parameters[name]);
                command.Parameters.Add(sqlParam);
            }

            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataSet ds = new DataSet();
            adapter.Fill(ds);

            return ds;

            
        }

        //public static void CloseSession()
        //{
        //    provider.CloseSession();
        //}

        //public static void CloseSessionFactory()
        //{
        //    provider.CloseSessionFactory();
        //}
    }
}